var employeeEditorFormDirty = false;
var currentlySelectedEmployee;
function setEmployeesView()
{

}

/*
Function that posts employee from the employeeeditorform
*/
function updateEmployee()
{
	if(employeeEditorFormDirty) // fix!
	{
		console.log('data have not been changed. Nothing to POST!');
		return;
	}

	$.ajax({
		type: 'PUT',
		url: '/pygem/api/v1.0/employees/' + $('#employeeeditorform #employeeid').val(),
		data: $('#employeeeditorform').serialize(),
		success: function(){
				//alert('{{_('you have saved employee details successfully!')}}');
				$('#employeesbrowser').trigger('employeemodified')
		},
		error: function (xhRequest, ErrorText, thrownError) {
        alert("Failed to process promotion correctly, please try again");
        console.log('xhRequest: ' + xhRequest + "\n");
        console.log('ErrorText: ' + ErrorText + "\n");
        console.log('thrownError: ' + thrownError + "\n");
    }
	}).done(function( msg )
	{
		alert( "Data Saved: " + msg );
		employeeEditorFormDirty = false; // Reset dirty flag, when data are posted
	});
	// add scrollTop if neccessary for employeeBrowser list
}

/*
employeeeditor form validation. Does not work yet.
*/
$('#employeeeditorform').validate({ // initialize the plugin
	rules: {
		employeefirstname: {
			required: true
		},
		employeesurname: {
			required: true
		}
	}
});

/*
* Function that bind events to main controls
*/
function bindEvents()
{
	/*
	Main events:
	1. employeechanged. This is triggered by leftmost list of employees (employeebrowser)
	2. employeemodified. When employee is modified and saved successfully, this event is trigered so
		we reload the list of employees.
	3. Each field of the employeeeditor form will catch keypress event. If data have not been changed
		POST will be ignored.
	*/

	/*When form is changed, we set dirty flag and mark appropriate label appending a star (*) */
	$('#employeeeditorform input').change(function()
	{
		employeeEditorFormDirty = true;
		console.log('data changed!' + $(this).attr('id'))
		var label = $('label[for="' + $(this).attr('name') + '"]')
		if(label.text().indexOf("*") == -1)
		{
			label.text(label.text() + '*');
		}
	});
	// When uses clicks on the list left (employeebrowser), employeechanged event is triggered
	$('#employeeeditor').on("employeechanged", function(event, param)
	{
		var id = param.substring(param.indexOf('_') + 1);
		//$(this).load('/employee/' + id);
		$.get( '/employee/' + id, function( data )
		{
			var employee = jQuery.parseJSON(data);
			$.each(employee, function(attrname, attrvalue)
			{
				if(attrname == 'employeegender')
				{
					$('#employeeeditorform #' + attrname + '_' + attrvalue).prop('checked', true);
				}
				else
				{
					$('#employeeeditorform #' + attrname).val(attrvalue);
				}
				var label = $('#employeeeditorform label[for="' + attrname + '"]')
				if(label)
				{
					label.text(label.text().replace("*", ""))
				}
			});
		});
		employeeEditorFormDirty = false; // new data! They aren't changed yet.
	});

	// When user clicks on a listelement, employeechanged event is triggered.
	$('.employeelistelement').click(function()
	{
		if(currentlySelectedEmployee)
		{
			currentlySelectedEmployee.removeClass('employeelistelementcurrentlyselected');
		}
		$('#employeeeditor').trigger("employeechanged", [$(this).attr('id')]);
		currentlySelectedEmployee = $(this);
		currentlySelectedEmployee.addClass('employeelistelementcurrentlyselected');
	});
	// Hovering, too, has some highlithing effects.
	$('.employeelistelement').hover(
		function()
		{
			$(this).addClass('employeelistelementactive')
		},
		function()
		{
			$(this).removeClass('employeelistelementactive')
		}
	);

	// On employeemodified, we reload (AJAX call) the employeebrowser list.
	$('#employeesbrowser').on("employemodified", function()
	{
		$(this).load('/employeeslist')
	});
}

// Employee Job Type
function updateEmployeeJobType(data)
{
	console.log('updating employee job type...' + data);
}

function createEmployeeJobType(data)
{
	console.log('create new employee job type...' + data);
}

// Employee Education
function updateEmployeeEducation(data)
{
	console.log('update employee education...' + data);
}

function createEmployeeEducation(data)
{
	console.log('create new employee education record...' + data);
}

function createJobsMenu()
{
	if(g_jobsMenu)
	{				
		$("#employeejob_edit_jobs_menu").html(g_jobsMenu);
	}
	else
	{
		$.get('/static/js/templates/jobtypes_menu.html', function(template)
		{
			var jobsArray = []
			for(jobID in g_jobsDict)
			{
				var job = g_jobsDict[jobID];
				var jobTypesArray = [];

				for(jobtypeID in job.jobtypes)
				{
					jobTypesArray.push(job.jobtypes[jobtypeID]);
				}
				job['jobtypes'] = jobTypesArray;
				jobsArray.push(job);
			}
			var rendered = Mustache.render(template, {'jobs': jobsArray});
			g_jobsMenu = rendered;			
			$("#employeejob_edit_jobs_menu").html(rendered);			
		}).fail(function(e){console.log(e);});

	}
}